package com.demo.common.exception;

import com.demo.common.base.ResultModel;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: ExceptionHandler
 * @Author: ChenXueLi
 * @Date: 2018-10-02 15:28
 */
@ControllerAdvice
@ResponseBody
public class BusinessExceptionResolve {

    private static Logger logger = Logger.getLogger(BusinessExceptionResolve.class);

    /**
     * 所有异常报错
     * @param request
     * @param exception
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    public ResultModel allExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception exception) throws Exception {
        ResultModel resultModel = new ResultModel();
        // 如果异常类型是自定义的异常，直接去除异常页面展示
        BusinessException businessExcetion = null;
        if (exception instanceof BusinessException) {
            businessExcetion = (BusinessException) exception;
        } else {
            // 如果异常类型不是系统自定义异常，构造一个自定义的异常类型（信息为‘系统异常’）
            if(exception.getStackTrace().length > 0){
                for(int i = 0; i < exception.getStackTrace().length; i++){
                    logger.error(exception.getStackTrace()[i]);
                }

            }else{
                logger.error(exception.toString());
            }

            businessExcetion = new BusinessException(-1, "系统异常,请联系管理员");
        }

        exception.printStackTrace();

        resultModel.setCode(businessExcetion.getCode());
        resultModel.setMessage(businessExcetion.getMessage());
        return resultModel;
    }

}
